﻿using demo1.Models.Database;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace demo1.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HomeController1 : ControllerBase
    {
        private readonly IMemoryCache cache;
        private readonly WebEnterpriseIIContext _db;
        public HomeController1(WebEnterpriseIIContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cache"></param>
        public HomeController1(IMemoryCache cache)
        {
            this.cache = cache;
        }
        [HttpGet]
        public ActionResult<string> TryGetValueCache()
        {
            if (cache.TryGetValue("UserName", out _))
            {
                return "该缓存存在";
            }
            else
            {
                return "该缓存不存在";
            }
        }
        [HttpGet]
        public ActionResult<string> SetCache()
        {
            cache.Set("UserName", "liudacheng");
            return "设置缓存成功";
        }
        public ActionResult<object> GetCache()
        {
            return cache.Get("UserName");
        }
        [HttpGet]
        public ActionResult<object> GetOrCreateCache()
        {
            return cache.GetOrCreate("UserName", x =>
            {
                var s = "liudacheng";
                return s + "11111";
            });

        }
        [HttpGet]
        public void RemoveCache()
        {
            cache.Remove("UserName");
        }
        [HttpGet]
        public ActionResult<string> CacheTime2()
        {
            string msg = string.Empty;
            cache.Set("UserName", "admin", new MemoryCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromSeconds(3)
            });
            for(int i = 1; i <= 5;i++)
            {
                msg += $"第{i}秒缓存值:{cache.Get<string>("UserName")}\n";
                Thread.Sleep(1000);
            }
            return msg;
        }
        [HttpGet]
        public List<Good> GetGoodList()
        {
            return _db.Goods.Where(x => x.Id >0).ToList();
        }
        [HttpGet]
        public Good GetGoodInfo(int goodId)
        {
            return _db.Goods.FirstOrDefault(x => x.Id == goodId);
        }
    }
}
